package org.csu.secondhand.api.controller.fronted;

import org.csu.secondhand.util.UploadUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/image")
public class ImageController {
    @PostMapping("upload")
    @ResponseBody
    public Map<Object, Object> upload(HttpServletRequest request) throws Exception {
        Map<Object, Object> map = new HashMap<>();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        InputStream ins = file.getInputStream();
        File toFile = new File(file.getOriginalFilename());
        UploadUtil.inputStreamToFile(ins, toFile);
        ins.close();
        String url = UploadUtil.getUrl(toFile);
        map.put("code", 0);
        map.put("msg", "SUCCESS");
        map.put("data", url);
        return map;
    }
}
